package com.example.larou.utils;

import cn.dev33.satoken.exception.SaTokenException;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;


@RestControllerAdvice
public class SaTokenExceptionHandler {

    // 处理 SaTokenException 异常
    @ExceptionHandler(SaTokenException.class)
    public ResponseEntity<Map<String, Object>> handleSaTokenException(SaTokenException e) {
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(getErrorResponse(e.getMessage()));
    }

    // 处理 NotLoginException 异常
    @ExceptionHandler(NotLoginException.class)
    public ResponseEntity<Map<String, Object>> handleNotLoginException(NotLoginException e) {
        if (e.getType().equals(NotLoginException.NOT_TOKEN)) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(getErrorResponse("重新登录"));
        }
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(getErrorResponse("登陆失败"));
    }

    // 处理 NotPermissionException 异常
    @ExceptionHandler(NotPermissionException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public ResponseEntity<Map<String, Object>> handleNotPermissionException(NotPermissionException e) {
        return ResponseEntity.status(HttpStatus.FORBIDDEN).body(getErrorResponse("没有访问权限"));
    }

    // 处理其他异常，返回500 Internal Server Error
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseEntity<Map<String, Object>> handleException(Exception e) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(getErrorResponse(e.getMessage()));
    }

    // 生成 JSON 格式的错误响应
    private Map<String, Object> getErrorResponse(String errorMessage) {
        Map<String, Object> response = new HashMap<>();
        response.put("code", HttpStatus.INTERNAL_SERVER_ERROR.value());
        response.put("msg", errorMessage);
        return response;
    }
}
